﻿<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="hanldleAdd()" v-if="hasPerm('servicesign.Add')">新建</a-button>
      <a-button
        v-if="hasPerm('servicesign.Delete')"
        type="primary"
        icon="minus"
        @click="handleDelete(selectedRowKeys)"
        :disabled="!hasSelected()"
        :loading="loading"
        >删除</a-button
      >
      <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button>
<div style="float:right">
      <a-breadcrumb style="margin-right:0px">
    <a-breadcrumb-item ><a @click="aclick(1)">首页</a></a-breadcrumb-item>
    <a-breadcrumb-item><a href="">客户列表</a></a-breadcrumb-item>
    <a-breadcrumb-item><a href="">服务商列表</a></a-breadcrumb-item>
    <a-breadcrumb-item><a>客户签约列表</a></a-breadcrumb-item>
  </a-breadcrumb>
</div>
    </div>

    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item label="查询类别">
              <a-select allowClear v-model="queryParam.condition">
                <a-select-option key="MID">客户ID</a-select-option>
                <a-select-option key="ServiceId">服务商ID</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input v-model="queryParam.keyword" placeholder="关键字" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-button
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }
              "
              >查询</a-button
            >
            <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-table
      ref="table"
      
      :columns="columns"
      :rowKey="(row) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :bordered="false"
      size="middle"
    >
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleEdit(record.Id)" v-if="hasPerm('servicesign.Edit')">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm
            title="确定删除吗？"
            v-if="hasPerm('servicesign.Delete')"
            ok-text="确定"
            cancel-text="取消"
            @confirm="handleDelete([record.Id])"
            @cancel="cancel"
          >
            <a href="#">删除</a>
          </a-popconfirm>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">
              更多操作
              <a-icon type="down" />
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item>
                  <a @click="contractInfo(record.Id)">合同附件</a>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
          <!-- <a class="ant-dropdown-link">
            更多操作
            
          </a> -->
        </template>
      </span>

      <template slot="UseStatus" slot-scope="text">
        <span v-if="text == '1'"><a-tag color="green">正常</a-tag></span>
        <span v-if="text == '0'"><a-tag color="red">失效</a-tag></span>
        <span v-if="text == '2'"><a-tag color="red">过期</a-tag></span>
      </template>
    </a-table>

    <edit-form ref="editForm" :parentObj="this"></edit-form>

    <!-- 协议配置 -->
    <a-modal title="协议配置" width="70%" :visible="Signvisible" :confirmLoading="loading" @cancel="SignviewCancel">
      <a-collapse accordion>
        <a-collapse-panel key="1" header="服务商信息">
          <a-form-model :model="Signserentity" v-bind="layout">
            <a-form-model-item label="服务商" prop="ServiceName">
              <a-select disabled show-search option-filter-prop="children" v-model="Signserentity.ServiceId"  :filter-option="filterOption">
            <a-select-option v-for="(item, index) in ServiceList" :key="index" :value="item.Id">
              {{ item.ServiceName }}
              </a-select-option>
          </a-select>
            </a-form-model-item>
            <a-form-model-item label="签约企业" prop="UnifiedSocialCreditCode">
              <a-select
            show-search
            disabled
            option-filter-prop="children"
            :filter-option="filterOption"
            v-model="Signserentity.MID"
          >
            <a-select-option v-for="item in cusList" :value="item.value" :key="item.value"> {{ item.text }} </a-select-option>
          </a-select>
            </a-form-model-item>
            <a-form-model-item label="协议日期" prop="LegalPersonName">
              <a-form-item
            :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }"
          >
            <a-date-picker style="width: 100%" format="yyyy-MM-dd" v-model="Signserentity.BeginDate"/>
          </a-form-item>
          <span :style="{ display: 'inline-block', width: '24px', textAlign: 'center' }"> - </span>
          <a-form-item :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
            <a-date-picker style="width: 100%" v-model="Signserentity.EndDate" format="yyyy-MM-dd"/>
          </a-form-item>
            </a-form-model-item>
          </a-form-model>
        </a-collapse-panel>
        <a-collapse-panel key="2" header="协议信息">
          <a-upload
            list-type="picture"
            :customRequest="selfUpload1"
            :default-file-list="abc"
            :multiple="false"
            :before-upload="beforeUpload"
          >
            <a-button> <a-icon type="upload" /> 选择协议 </a-button>
          </a-upload>
          <div>
            <a-button @click="submitContrat">保存合同</a-button>
          </div>
          <a-table
            ref="table"
            :columns="Signcolumns"
            :rowKey="(row) => row.Id"
            :dataSource="SignData"
            :loading="loading"
            :bordered="false"
            size="middle"
          >
            <span slot="action" slot-scope="text, record">
              <template>
                <a-popconfirm
                v-if="hasPerm('signfile.Delete')"
                  title="确定删除吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="SignDelete([record.Id])"
                  @cancel="cancel"
                >
                  <a href="#">删除</a>
                </a-popconfirm>
                <a-divider type="vertical" />
                <a @click="downfile(record)">下载协议</a>
              </template>
            </span>
          </a-table>
        </a-collapse-panel>
      </a-collapse>
      <template slot="footer">
        <a-button @click="SignviewCancel">关闭</a-button>
      </template>
    </a-modal>
  </a-card>
</template>

<script>
import EditForm from './EditForm'
import OperatorCache from '@/utils/cache/OperatorCache'
const Signcolumns = [
  { title: '文件名称', dataIndex: 'FileName', width: '30%' },
  { title: '上传时间', dataIndex: 'CreateTime', width: '30%' },
  { title: '操作人', dataIndex: 'CreatorId', width: '30%' },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' } },
]
const columns = [
  { title: '客户名称', dataIndex: 'customerName', width: '15%' },
  // { title: '服务商ID', dataIndex: 'ServiceId', width: '10%' },
  { title: '开始日期', dataIndex: 'BeginDate', width: '20%' },
  { title: '终止日期', dataIndex: 'EndDate', width: '20%' },
  { title: '费率标准(%)', dataIndex: 'Rate', width: '15%' },
  { title: '签约状态', dataIndex: 'UseStatus', width: '15%', scopedSlots: { customRender: 'UseStatus' } },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' } },
]

export default {
  components: {
    EditForm,
  },
  mounted() {
    this.getDataList()
  },
  data() {
    return {
      abc:[],
      Signcolumns,
      SignData:[],
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 },
      },
      data: [],
      pagination: {
        current: 1,
        pageSize: 10,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
      },
      cusList:[],
      ServiceList:[],
      Signvisible:false,
      filters: {},
      sorter: { field: 'Id', order: 'asc' },
      loading: false,
      columns,
      queryParam: {},
      selectedRowKeys: [],
      Signserentity:{}
    }
  },
  methods: {
    beforeUpload(file) {
      let fileType = file.name.split('.')
      const fileDate = fileType.slice(-1)
      if (['xlsx', 'xls', 'doc', 'docx', 'pdf'].indexOf(fileDate[0]) < 0) {
        this.$message.error('仅支持doc,docx,pdf,xls,xlsx 格式')
        return false
      }
    },
    submitContrat() {
      if (this.abc.length <= 0) {
        this.$message.error('请先选择需要上传合同')
      } else if (this.abc.length == 1) {
        let temp = {}
        temp.Rid = this.Signserentity.FileAttId
        temp.FileName = this.abc[0].name
        temp.FilePathUrl = this.abc[0].uid
        temp.UpUserName = OperatorCache.info['UserName']
        temp.UpUserId = OperatorCache.info['Id']
        temp.ContractdownUrl = this.abc[0].url
        this.$http.post('/Base_leasesystem_signfile/leasesystem_signfile/SaveData', temp).then((res) => {
          if (res.Success) {
            this.$message.success('操作成功')
            if (this.Signserentity.FileAttId) {
              this.flushSign('Rid', this.Signserentity.FileAttId)
              this.abc= []
            }
          } else {
            this.$message.error('操作失败')
          }
        })
        console.log(temp)
      } else {
        this.$message.error('单次上传一个文件，可删除后重新上传')
      }
    },
    selfUpload1({ action, file, onSuccess, onError, onProgress }) {
      this.loading = true
      const formData = new FormData()
      let that = this
      formData.append('file', file)
      this.$http.post('/Base_Manage/Upload/UploadFileByForm', formData).then((res) => {
        this.abc.push(res)
        this.loading = false
      })
    },
    SignDelete(row) {
      this.$http.post('/Base_leasesystem_signfile/leasesystem_signfile/DeleteData', row).then((res) => {
        if (res.Success) {
          this.$message.success('操作成功')
          this.flushSign('Rid', this.Signserentity.FileAttId)
        } else {
          this.$message.error('操作失败')
        }
      })
    },
    downfile(row) {
      let index = row.ContractdownUrl.lastIndexOf('Upload')
      let spl = row.ContractdownUrl.substr(index)

      this.$http.post('/Base_Manage/Upload/downSign', { id: spl }, { responseType: 'blob' }).then((res) => {
        const blob = new Blob([res])
        const fileName = row.FileName
        const elink = document.createElement('a') // 创建a标签
        elink.download = fileName // 为a标签添加download属性
        // a.download = fileName; //命名下载名称
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click() // 点击下载
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink) // 释放标签
      })
    },
    flushSign(condition, keyword) {
      let temp = {}
      temp.condition = condition
      temp.keyword = keyword
      this.$http.post('/Base_leasesystem_signfile/leasesystem_signfile/GetDataList', { Search: temp }).then((res) => {
        console.log(res)
        this.SignData = res.Data
      })
    },
    GetService(){
      this.$http.post("/Base_Manage/Home/GetService_Select").then((res)=>{
        this.ServiceList = res.Data
      })
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
      this.getDataList()
    },
    getDataList() {
      this.selectedRowKeys = []

      this.loading = true
      this.$http
        .post('/Base_leasesystem_servicesign/leasesystem_servicesign/GetAll', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: this.queryParam,
          ...this.filters,
        })
        .then((resJson) => {
          this.loading = false
          this.data = resJson.Data
          const pagination = { ...this.pagination }
          // pagination.total = resJson.Total
          this.pagination = pagination
        })
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    hanldleAdd() {
      this.$refs.editForm.openForm()
    },
    handleEdit(id) {
      this.$refs.editForm.openForm(id)
    },
    handleDelete(ids) {
      var thisObj = this

      return new Promise((resolve, reject) => {
        thisObj.$http.post('/Base_leasesystem_servicesign/leasesystem_servicesign/DeleteData', ids).then((resJson) => {
          resolve()

          if (resJson.Success) {
            thisObj.$message.success('操作成功!')

            thisObj.getDataList()
          } else {
            thisObj.$message.error(resJson.Msg)
          }
        })
      })
    },
    cancel(e) {
      this.$message.error('已取消删除')
    },
    SignviewCancel(){
      this.Signvisible = false
    },
    async contractInfo(id) {
      this.abc = []
      this.GetService()

      
     await this.$http
          .post('/Base_leasesystem_servicesign/leasesystem_servicesign/GetTheData', { id: id })
          .then(res=>{
            this.Signserentity = res.Data
            this.Signserentity.BeginDate = this.$moment(res.Data.BeginDate, 'YYYY-MM-DD')
            this.Signserentity.EndDate = this.$moment(res.Data.EndDate, 'YYYY-MM-DD')
            
          })
      if (this.Signserentity.FileAttId) {
        this.flushSign('Rid', this.Signserentity.FileAttId)
      }
      this.$http
          .post('/Base_leasesystem_merchant/leasesystem_merchant/FullSelect')
          .then((resJson) => {
            this.cusList = resJson.Data
          })
      this.Signvisible = true
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    aclick(val){
      if(val == 1){
        this.$router.push({ path: '/' })
      }
    }
  },
}
</script>

<style>
.ant-table-thead > tr > th
{
  font-weight: 600;
  color: #333333;
}
</style>

